<?php

namespace controller;

require_once('/model/Loginmodel.php');
require_once('/view/UserInfo.php');
require_once('/view/Loginview.php');
require_once('/view/HTMLView.php');

class userLogin {
	/**
	 * @var \view\UserInfo
	 */
	private $usrInfoView;
	
	/**
	 * @var \model\Loginmodel
	 */
	private $loginM;
	
	/**
	 * @var \view\Loginview
	 */
	private $loginView;
	
	/**
	 * @var \view\HTMLView
	 */
	private $pageView;
	
	private static $arrayusername = "username";
	private static $arraypassword = "password";

	function __construct() {
		$this->usrInfoView = new \view\UserInfo();
		$this->loginM = new \model\Loginmodel();
		$this->loginView = new \view\Loginview();
		$this->pageView = new \view\HTMLView();
	}

	/**
	 * En funktion som loggar in eller loggar ut användaren.
	 * @return string HTML
	 */
	public function loginUser() {
		if($this->loginView->getLogoutInfo()) {
			return $this->logoutUser();
		} 
		if($this->usrInfoView->sessionSet()) {
			return $this->pageView->getMemberPage();
		} 
		if($this->usrInfoView->cookieIsset()) {
			$cookie = $this->usrInfoView->getCookieInfo();
			$userName = $cookie[self::$arrayusername];
			$userPW = $cookie[self::$arraypassword];
			if($this->loginM->loginUserWithCookie($userName, $userPW)) {
				$this->pageView->setCookieLoginSuccesMessage();
				$this->loginView->setSessionLogin();
				return $this->pageView->getMemberPage();
			} else {
				$this->pageView->setWrongCookieInfoMessage();
				return $this->pageView->getLoginPage();
			}
		} 
		if ($this->loginView->getLoginInfo()) {
			try {
				$userName = $this->usrInfoView->getUserName();
				$userPW = $this->usrInfoView->getUserPW();
				$this->loginM->validateUsrInfo($userName, $userPW);
				$this->loginView->setSessionLogin();
				if($this->usrInfoView->getRememberData()) {
					$this->saveUser();
					$this->pageView->setCookieFirstTimeLoginSuccess();
				} else {
					$this->pageView->setLoginSuccesMessage();
				}
				return $this->pageView->getMemberPage();
			} catch (\Exception $e) {
				if($e->getMessage() == "1") {
					$this->pageView->setUserNameMissing();
				} else if($e->getMessage() == "2") {
					$this->pageView->setPasswordMissing();
				} else if($e->getMessage() == "3") {
					$this->pageView->setWrongUserCredentials();
				}
				$this->pageView->setInputValue();
			}
		}
		return $this->pageView->getLoginPage();
	}

	/**
	 * @return string HTML
	 * Funktion som tar bort alla cookies och loggar ut användaren.
	 */
	public function logoutUser() {
		$this->usrInfoView->removeUsr();
		$this->pageView->setLogoutMessage();
		session_destroy();
		return $this->pageView->getLoginPage();
	}

	/**
	 * Funktion som sparar användaruppgifter.
	 */
	public function saveUser() {
		$this->usrInfoView->saveUserToCookie();
	}
}
?>